package com.asset.dispoal.file.agreementCaseData.service.commom;

import com.alibaba.excel.EasyExcel;
import com.asset.dispoal.business.bsAgreement.domain.db.mapper.AgreementMapper;
import com.asset.dispoal.business.bsAgreement.service.commom.AgreementAbolishCaseCommand;
import com.asset.dispoal.file.agreementCaseData.dto.ImportAbolishCaseRequest;
import com.asset.dispoal.file.evidenceRecognition.domain.dto.ContractNo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author qr
 * @date 2022/4/6$
 */
@Component
public class ImportAbolishCaseCommand implements BaseCommand<ImportAbolishCaseRequest, Result> {


    @Autowired
    AgreementMapper agreementMapper;

    @Autowired
    AgreementAbolishCaseCommand agreementAbolishCaseCommand;

    @SneakyThrows
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(ImportAbolishCaseRequest request) {
        List<ContractNo> contractNoList = EasyExcel.read(request.getFile().getInputStream()).head(ContractNo.class).sheet().doReadSync();
        List<String> contractNoStrList = contractNoList.stream().map(ContractNo::getContractNo).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(contractNoStrList)) {
            return Result.faild("导入的合同号不存在");
        }
        List<String> agreementIdList = agreementMapper.queryAgreementByNo(contractNoStrList, request.getAssetInstBatchId());
        if (CollectionUtil.isEmpty(agreementIdList)) {
            return Result.faild("导入的合同号不存在");
        }
        //查询默认废案原因
        String reasonId = agreementMapper.getDefaultAbolishedReasonId();
        for (String agreementId : agreementIdList) {
            agreementAbolishCaseCommand.execute(agreementId, reasonId);
        }
        return Result.ok();
    }
}
